<?php

declare (strict_types = 1);

namespace app\common\service;

use app\common\service\BaseService;
use app\common\exception\AdminException;
use app\common\repository\VersionRepository;

class VersionService extends BaseService
{
   public function __construct(VersionRepository $repository)
   {
       $this->repository = $repository;
   }

    /**
     * 获取应用升级列表
     *
     * @param array $params
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     */
    public function getList(array $params = []): array
    {
        [$page, $pageSize] = $this->getPaginationParams();
        $where = [];
        if(!empty($params['version'])){
            $where[] = ['version', 'like', '%'.$params['version'].'%'];
        }
        return $this->repository->paginate($where, ['id' => 'desc'], $page, $pageSize);
    }

    /**
     * 获取应用版本详情信息
     *
     * @param $id
     * @return \app\common\model\BaseModel|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getInfo($id): ?\app\common\model\BaseModel
    {
        return $this->repository->getOne($id);
    }

    /**
     * 创建应用版本信息
     *
     * @param array $data
     * @return \app\common\model\BaseModel|array
     * @throws \Exception
     */
    public function create(array $data): \app\common\model\BaseModel|array
    {
        return $this->repository->save($data);
    }

    /**
     * 更新应用版本信息
     * 
     * @param array $data
     * @param $id
     * @return bool|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function update(array $data, $id): bool|int
    {
        if(empty($id)) {
            throw new AdminException('ID 不能为空');
        }
        return $this->repository->update($data, $id);
    }

    /**
     * 删除应用版本信息
     *
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function delete($id): bool
    {
        return $this->repository->delete($id);
    }

    /**
     * 检查应用版本升级
     *
     * @param $version
     * @return array|\app\common\model\BaseModel|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
   public function checkVersion($data): array|\app\common\model\BaseModel|null
   {
       // 1. 参数校验
       if (empty($data)) {
           throw new AdminException('检查升级异常，请稍后重试！');
       }

       $currentVersion = $data['version'] ?? '';
       $platform = $data['platform'] ?? 'ios';

       if (!in_array($platform, ['ios', 'android'])) {
           throw new AdminException('无效的平台');
       }

       if (empty($currentVersion)) {
           throw new AdminException('缺少当前版本号');
       }

       // 2. 查询最新启用的版本
       try {
           $versionInfo = $this->repository->getOne(
               ['status' => 1, 'platform' => $platform],
               ['*'],
               ['create_time' => 'desc']
           );

           if (!$versionInfo) {
               return [
                   'msg'  => '当前已是最新版本',
                   'has_update' => false
               ];
           }

           // 3. 语义化版本比较
           $needUpdate = version_compare($versionInfo['version'], $currentVersion, '>');

           if (!$needUpdate) {
               return [
                   'msg'  => '当前已是最新版本',
                   'has_update' => false
               ];
           }

           // 4. 返回更新信息
           return [
               'msg'  => '发现新版本',
               'has_update'     => true,
               'version'        => $versionInfo['version'],
               'versionCode'    => $versionInfo['versionCode'],
               'content'        => $versionInfo['content'],
               'type'           => (int)$versionInfo['type'], // 1: 全量, 0: 差量
               'force_update'   => (bool)$versionInfo['force_update'],
               'download_url'   => $versionInfo['download_url'],
               'create_time'    => $versionInfo['create_time'],
           ];

       } catch (\Throwable $e) {
           // 记录日志
           \think\facade\Log::error('检查版本更新失败: ' . $e->getMessage());
           throw new AdminException('检查升级异常，请稍后重试！', 500);
       }
   }
}